#! /usr/bin/python
import socket
import sys
import traceback
import os
import re
import time
import cPickle
from backupManager.file import file
from time import sleep
import math
import datetime
import Pyro.core
import traceback

host = ''
port = 59999
backlog = 5
buffer_size = 8192
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
NOTEXIST='notexist'

class indexServer(Pyro.core.ObjBase):
	def __init__(self):
		Pyro.core.ObjBase.__init__(self)

	def index(self,commDict):
		return indexDrive(commDict)



def indexDrive(commDict):
    print 'Received index request',str(datetime.datetime.now()),commDict
    if not os.path.exists(commDict['path']):
	return NOTEXIST
    if commDict['validext']:
        validext = '|'.join(commDict['validext'])
        validext = "\.(" + validext + ")$"
    else:
        validext = None
    if commDict['skip']:
    	skip = '|'.join(commDict['skip'])
    	skip = re.compile(skip,re.IGNORECASE)
    else:
	skip = None
    try:
	if len(commDict['paths']) > 1 or (len(commDict['paths']) == 1 and commDict['paths'][0] != commDict['sep']):
		result = file('',os.sep,commDict['name']+":",True,0,0,commDict['name'],commDict['serial'])
		files = []
		for path in commDict['paths']:
			path = path.replace(commDict['sep'],os.sep)
			path = unicode(path)
			newFile = index(path,validext,skip,root=True,commDict=commDict)
			files.append(newFile)
		result.setFiles(files)
	else:
		result = index(unicode(os.sep),validext,skip,root=True,commDict=commDict)
    except:
	exc_type, exc_value, exc_traceback = sys.exc_info()
	traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout)
	result = None
    print 'Done indexing!',str(datetime.datetime.now())
    return result

def index(path,validext,skip,root=False,commDict=None):
    dir = commDict['path'] + os.sep + path
    while re.search(r'/$',dir,re.IGNORECASE):
	dir = re.sub(r'/$','',dir)
    if not os.path.isdir(dir):
        print "Can only call index on a directory!\n"
        return None
    try:
        files = os.listdir(dir)
    except:
        return None
    dirObj = file(os.path.basename(dir),
		os.path.dirname(os.path.join(commDict['path'],path)).replace(commDict['path'],'').replace(os.sep,commDict['sep']),
		commDict['name']+":",
		True,
		0,
		0,
		commDict['name'],
		commDict['serial'])
    passedFiles = []
    if validext:
        ext = re.compile(validext,re.IGNORECASE)
    else:
        ext = None
    for foundFile in files[:]:
        if os.path.islink(os.path.join(dir,foundFile)):
            realFile = os.readlink(os.path.join(dir,foundFile))
        else:
            realFile = os.path.join(dir,foundFile)
	if skip:
        	if re.search(skip,foundFile):
        		continue
        if not os.path.isdir(realFile):
            if validext:
                if not re.search(ext,foundFile):
                    continue
        newFile = None
        if os.path.isdir(realFile):
            newFile = index(os.path.join(path,foundFile),validext,skip,commDict=commDict)
        else:
	    mtime = int(math.floor(os.path.getmtime(os.path.join(dir,foundFile))))
	    if mtime%2:
		mtime+=1
            newFile = file(foundFile,
			path.replace(os.sep,commDict['sep']),
			commDict['name']+":",
			False,
			float(os.path.getsize(os.path.join(dir,foundFile)))/float(1024),
			mtime,
			commDict['name'],
			commDict['serial'])
        if newFile:
            newFile.setParent(dirObj)
            passedFiles.append(newFile)
    if not passedFiles and not root:
        return None
    dirObj.setFiles(passedFiles)
    return dirObj

def main():
	Pyro.core.initServer()
	daemon = Pyro.core.Daemon(port=(port))
	uri=daemon.connect(indexServer(),'indexserver')
	print 'The daemon runs on port:',daemon.port
	print 'The object\'s uri is:',uri
	daemon.requestLoop()

if __name__ == "__main__":
	main()
